import { ref, reactive, markRaw } from 'vue';
import { removeUndefinedParams } from '@/utils/index';
import type { SearchOptionsType, TableFieldsSettingType } from '@/components/CPageTable';
import { getReportList } from '@/apis/eci/reportFormManagement/reportFormManagement';
import type { GetListEmissionTaskResult } from '@/apis/eci/emissionAccounting/model/detailModel';
import { VxeTablePropTypes } from '@xfchenju/vxe-table';
import { ColumnSettingTypeEnum } from '@/components/CPageTable';
import { CTableProps } from '@/components/CTable/index';
import { nextTick } from 'process';
import { useRoute } from 'vue-router';
import { CarbonInventoryStandardsMap } from '@/constants/enum';

interface SearchListFillTaskType extends GetListEmissionTaskResult {
  label: string;
  value: any;
}

export const useDetail = (
  onSearchFormCodeChange: (list: GetListEmissionTaskResult[]) => void,
  handleUploadFields: (fieldsSetting: TableFieldsSettingType[]) => void,
  handleExpandAll: () => void
) => {
  const route = useRoute();
  const { standard, inventoryYear, orgName, orgCode, gwpVersion } = route.query;
  const standardStr =
    CarbonInventoryStandardsMap[standard as keyof typeof CarbonInventoryStandardsMap] +
    `${gwpVersion ? `(${gwpVersion})` : ''}`;
  const title = `${orgName}_${inventoryYear}_${standardStr}_统计报表`;
  // 搜索字段及其他
  const searchForm = reactive({
    organizationCode: (orgCode as string) || '',
    inventoryYear: (inventoryYear as string) || '',
    standard: (standard as string) || ''
  });
  /**
   * 接口返回的全量的入参列表（处理过字段名称了）
   */
  const apiResParamsList = ref<SearchListFillTaskType[]>([]);
  /**
   * 显示在页面上的入参列表
   */
  const pageShowParamsList = ref<SearchListFillTaskType[]>([]);
  // 搜索配置
  const searchOptions: SearchOptionsType[] = markRaw([]);
  const tableConfig = reactive({
    treeConfig: {
      expandAll: true,
      children: 'children',
      iconOpen: 'c-mian-xia iconfont',
      iconClose: 'c-mian-you iconfont'
    } as VxeTablePropTypes.TreeConfig
  });
  /**
   * 表格配置
   */
  const tableOptions: CTableProps = {
    pagination: false,
    immediate: true,
    loadData,
    border: true,
    extraTableOption: {
      treeConfig: tableConfig.treeConfig
    }
  };
  async function loadData(): Promise<any> {
    // 如果参数不全，则列表为空
    if (!searchForm.organizationCode || !searchForm.inventoryYear || !searchForm.standard) {
      return Promise.resolve({
        records: [],
        total: 0
      });
    }
    const params = handleParams();
    return getReportList(params).then(res => {
      const head = handleHeaderSet(res.headList);
      console.log('head', head);
      nextTick(() => {
        // 更新表格列字段
        handleUploadFields([
          {
            title: '组织名称',
            field: 'organizationName',
            slot: 'organizationNameSlot',
            minWidth: 200,
            columnSettingConfig: {
              enabled: true,
              type: ColumnSettingTypeEnum.REQUIRED
            },
            treeNode: true
          },
          ...head,
          {
            title: '全价值链总排放(tCO₂e)',
            field: 'totalEmission',
            slot: 'totalEmissionSlot',
            minWidth: 180,
            align: 'right',
            fixed: 'right',
            columnSettingConfig: {
              enabled: true,
              type: ColumnSettingTypeEnum.REQUIRED
            }
          },
          {
            title: '占比(%)',
            field: 'proportion',
            slot: 'proportionSlot',
            minWidth: 100,
            fixed: 'right',
            columnSettingConfig: {
              enabled: true,
              type: ColumnSettingTypeEnum.REQUIRED
            }
          }
        ]);
        // 展开所有节点
        nextTick(() => {
          handleExpandAll();
        });
      });
      if (res.reportDataList?.length) {
        return {
          records: res.reportDataList,
          total: res.reportDataList.length
        };
      } else {
        return {
          records: [],
          total: 0
        };
      }
    });
  }

  // 处理参数
  const handleParams = () => {
    // 参数
    let params = {
      orgCode: searchForm.organizationCode,
      inventoryYear: searchForm.inventoryYear,
      standard: searchForm.standard
    };
    params = removeUndefinedParams(params);
    return params;
  };
  /**
   * 初始列配置
   */
  const tableFieldsSetting: TableFieldsSettingType[] = [
    {
      title: '组织名称',
      field: 'organizationName',
      slot: 'organizationNameSlot',
      minWidth: 200,
      columnSettingConfig: {
        enabled: true,
        type: ColumnSettingTypeEnum.REQUIRED
      },
      treeNode: true
    },
    {
      title: '全价值链总排放(tCO₂e)',
      field: 'totalEmission',
      slot: 'totalEmissionSlot',
      minWidth: 180,
      fixed: 'right',
      columnSettingConfig: {
        enabled: true,
        type: ColumnSettingTypeEnum.REQUIRED
      }
    },
    {
      title: '占比(%)',
      field: 'proportion',
      slot: 'proportionSlot',
      minWidth: 100,
      fixed: 'right',
      columnSettingConfig: {
        enabled: true,
        type: ColumnSettingTypeEnum.REQUIRED
      }
    }
  ];

  function handleHeaderSet(headList: any[]): any[] {
    const res = [];
    for (let i = 0; i < headList.length; i++) {
      const item = headList[i];
      if (item.children?.length) {
        const setItem: any = {
          title: item.headName
        };
        const totalItem = {
          title: '总排放量',
          key: item.headCode,
          field: `valueMap.${item.headCode}`,
          minWidth: 150,
          align: 'right',
          columnSettingConfig: {
            enabled: item.defaultShow
          }
        };
        const setRes = handleHeaderSet(item.children);
        setRes.splice(0, 0, totalItem);
        Object.assign(setItem, {
          children: setRes
        });
        console.log('setRes', setRes, setItem);
        res.push(setItem);
      } else {
        const setItem = {
          title: item.headName,
          key: item.headCode,
          field: `valueMap.${item.headCode}`,
          align: 'right',
          minWidth: 150,
          columnSettingConfig: {
            enabled: item.defaultShow
          }
        };
        res.push(setItem);
      }
    }
    return res;
  }

  return {
    searchForm,
    searchOptions,
    tableOptions,
    handleParams,
    tableFieldsSetting,
    title
  };
};

/**
 * 处理接口返回的数据列表
 * @param res
 * @returns
 */
function handleListParamsFormat(res: any[]) {
  const list: SearchListFillTaskType[] = [];
  for (let i = 0; i < res.length; i++) {
    const item = res[i];
    list.push({
      label: item.organizationName,
      value: item.organizationCode,
      ...item
    });
  }
  return list;
}

/**
 * 前端搜索功能
 * @param query
 * @param list
 * @returns
 */
function handleQueryListParams(query: string, list: SearchListFillTaskType[]) {
  const res: SearchListFillTaskType[] = [];
  list?.forEach(item => {
    if (item.organizationName.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) > -1) {
      res.push({
        ...item
      });
    }
  });
  return res;
}
